import requests
import time
import random

class BubbleSortClient:
    def __init__(self, base_url="http://localhost:8000"):
        self.base_url = base_url
    
    def sort(self, array: list, ascending=True) -> dict:
        """请求排序服务"""
        try:
            response = requests.post(
                f"{self.base_url}/bubble_sort",
                json={
                    "array": array,
                    "ascending": ascending
                },
                timeout=5.0
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {str(e)}")
            raise

def generate_random_array(size=10):
    return [random.randint(1, 100) for _ in range(size)]

def run_demo():
    client = BubbleSortClient()
    
    print("冒泡排序演示")
    print("=" * 40)
    
    # 测试小数组
    small_array = [64, 34, 25, 12, 22, 11, 90]
    print(f"原始数组: {small_array}")
    
    start = time.time()
    result = client.sort(small_array)
    elapsed = time.time() - start
    
    print(f"排序后(升序): {result['sorted_array']}")
    print(f"迭代次数: {result['iterations']}")
    print(f"交换次数: {result['swaps']}")
    print(f"耗时: {elapsed:.6f}秒\n")
    
    # 测试大数组
    large_array = generate_random_array(100)
    print(f"大数组(前10个): {large_array[:10]}...")
    
    start = time.time()
    result = client.sort(large_array, ascending=False)
    elapsed = time.time() - start
    
    print(f"排序后(降序，前10个): {result['sorted_array'][:10]}...")
    print(f"迭代次数: {result['iterations']}")
    print(f"交换次数: {result['swaps']}")
    print(f"耗时: {elapsed:.6f}秒")

if __name__ == "__main__":
    run_demo()